//
//  Emoticon.swift
//  表情键盘独立开发
//
//  Created by IOS on 15/8/11.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit

class EmoticonPackage: NSObject {
    ///目录名
    var id: String = ""
    ///分组名
    var groupName: String = ""
    ///表情数组
    var emoticons: [Emoticon]?
    
    init(id: String, groupName: String = "") {
        self.id = id
        self.groupName = groupName
    }
    
    //添加最近使用的表情
    class func addFavorate(emoticon: Emoticon) {
        
        if emoticon.removeEmoticon {
            return
        }
        
        //拿到第0个分组包的数组
        var ems = packages[0].emoticons
        //删除最后一个删除按钮
        ems?.removeLast()
        //记录表情使用的次数
        emoticon.times++
        //判断表情是否存在
        let contains = ems!.contains(emoticon)
        if !contains {
            ems?.append(emoticon)
        }
        //排序表情数组
       ems = ems!.sort({ (e1, e2) -> Bool in
            return e1.times > e2.times
        })
        
        if !contains {
            ems?.removeLast()
        }
        //重新追加删除按钮
        ems?.append(Emoticon(remove: true))
        
        packages[0].emoticons = ems
    }
    
    ///使用静态常量只允许设置一次数值。变量的写法和单例 的方法几乎一样
    static let packages = EmoticonPackage.loadPackages()
    ///加载所有表情包
    class func loadPackages() -> [EmoticonPackage] {
        
        let path = (bundlePath as NSString).stringByAppendingPathComponent("emoticons.plist")
        
        let dict = NSDictionary(contentsOfFile: path)!
        let array = dict["packages"] as! [[String: AnyObject]]
        
//        print(array)
        
        var arrayM = [EmoticonPackage]()
        
        //插入最近表情包
        let package = EmoticonPackage(id: "", groupName: "最近").appendEmptyEmoticons()
        arrayM.append(package)
        
        for d in array {
            let id = d["id"] as! String
            let package = EmoticonPackage(id: id).loadEmoticon().appendEmptyEmoticons()
            arrayM.append(package)
        }
        
        return arrayM
        
    }
    
    func loadEmoticon() -> Self {
        let path = ((EmoticonPackage.bundlePath as NSString).stringByAppendingPathComponent(id) as NSString).stringByAppendingPathComponent("info.plist")
        let dict = NSDictionary(contentsOfFile: path)!
        
        groupName = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String: String]]
        
        emoticons = [Emoticon]()
        var index = 0
        for d in array {
            emoticons?.append(Emoticon(id: id, dict: d))
            index++
            
            if index == 20 {
                emoticons?.append(Emoticon(remove: true))
                index = 0 
            }
        }
        
        
        return self
    }
    
    ///在表情数组中追加空白表情
    func appendEmptyEmoticons() -> Self {
        
        if emoticons == nil {
            emoticons = [Emoticon]()
        }
        
        let count = (emoticons?.count)! % 21
        print("已经有 \(count) 个表情")
        
        if count > 0 || emoticons?.count == 0{
            for _ in count..<20 {
                emoticons?.append(Emoticon(remove: false))
                
            }
            emoticons?.append(Emoticon(remove: true))
        }
        
        return self
    }
    
    
    static let bundlePath = (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons.bundle")
    override var description: String {
        return "\(id)\(groupName)\(emoticons)"
    }
    
}


class Emoticon: NSObject {

    /// 表情目录
    var id: String?
    ///被点击的次数
    var times = 0
    /// 发送给服务器的表情文字
    var chs: String?
    /// 本地显示图片文件名
    var png: String?
    ///图片完整路径
    var imagePath: String {
        //判断是否是图片
        if chs == nil {
            return ""
        }
        return ((EmoticonPackage.bundlePath as NSString).stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(png!)
        
    }
    
    /// emoji 的代码
    var code: String? {
        didSet {
            //扫描器
            let scanner = NSScanner(string: code!)
            var value: UInt32 = 0
            scanner.scanHexInt(&value)
            emoji = String(Character(UnicodeScalar(value)))
        }
    }
    
    /// emoji 字符串
    var emoji: String?
    ///删除按钮标记
    var removeEmoticon = false
    init(remove: Bool) {
        removeEmoticon = remove
    }
    
    init(id: String, dict: [String: String]) {
        self.id = id
        
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    override var description: String {
        return "\(chs)\(png)\(code)"
    }
    
}









